package cn.iocoder.yudao.module.im.controller.app.member;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.im.service.member.MemberConversationService;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import javax.validation.*;
import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.im.enums.ErrorCodeConstants.IM_DISABLED_TIME;
import static cn.iocoder.yudao.module.im.enums.ErrorCodeConstants.IM_POINT_NOT_EXISTS;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.AUTH_LOGIN_USER_DISABLED;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.USER_NICKNAME_EMPTY;

import cn.iocoder.yudao.module.im.controller.app.member.vo.*;
import cn.iocoder.yudao.module.im.dal.dataobject.member.MemberMessageDO;
import cn.iocoder.yudao.module.im.service.member.MemberMessageService;

@Tag(name = "用户 APP - IM消息")
@RestController
@RequestMapping("/im/member-message")
@Validated
public class AppMemberMessageController {

    @Resource
    private MemberMessageService memberMessageService;

    @Resource
    private MemberConversationService memberConversationService;

    @Resource
    private MemberUserApi memberUserApi;

    @PostMapping("/send")
    @Operation(summary = "发送IM消息")
    @PreAuthenticated
    public CommonResult<Long> sendImMessage(@Valid @RequestBody AppMemberMessageSaveReqVO createReqVO) {
        createReqVO.setSendUserId(getLoginUserId());
        return success(memberMessageService.sendImMessage(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新IM消息")
    public CommonResult<Boolean> updateMemberMessage(@Valid @RequestBody AppMemberMessageSaveReqVO updateReqVO) {
        memberMessageService.updateMemberMessage(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除IM消息")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteMemberMessage(@RequestParam("id") Long id) {
        memberMessageService.deleteMemberMessage(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得IM消息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<AppMemberMessageRespVO> getMemberMessage(@RequestParam("id") Long id) {
        MemberMessageDO memberMessage = memberMessageService.getMemberMessage(id);
        return success(BeanUtils.toBean(memberMessage, AppMemberMessageRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得IM消息分页")
    @PreAuthenticated
    public CommonResult<PageResult<AppMemberMessageRespVO>> getMemberMessagePage(@Valid AppMemberMessagePageReqVO pageReqVO) {
        pageReqVO.setSendUserId(getLoginUserId());
        PageResult<MemberMessageDO> pageResult = memberMessageService.getMemberMessagePage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }

        // 拼接关联数据
        Map<Long, MemberUserRespDTO> sendUserMap = memberUserApi.getUserMap(convertList(pageResult.getList(), MemberMessageDO::getSendUserId));

        return success(BeanUtils.toBean(pageResult, AppMemberMessageRespVO.class, message -> message
                .setSendNickName(sendUserMap.getOrDefault(message.getSendUserId(), new MemberUserRespDTO()).getNickname())
                .setSendAvatar(sendUserMap.getOrDefault(message.getSendUserId(), new MemberUserRespDTO()).getAvatar()))
        );
    }

    @PostMapping("/update-read-status")
    @Operation(summary = "更新IM消息已读状态")
    @Parameter(name = "messageId", description = "消息ID", required = true)
    @PreAuthenticated
    public CommonResult<Boolean> updateImMessageReadStatus(@RequestParam("messageId") Long messageId) {
        memberMessageService.updateImMessageReadStatus(messageId, getLoginUserId());
        // 更新会话未读
        memberConversationService.updateUnReadCount(messageId);
        return success(Boolean.TRUE);
    }

}